package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findMaxScoreRecommendUser(Long toUserId) {
        // 1.构建条件
        Query query = Query.query(Criteria.where("toUserId").is(toUserId)) // 登录人id
                .with(Sort.by(Sort.Order.desc("score"))) // 缘分值倒序
                .skip(0).limit(1); // 查询第一条
        // 2.查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        // 3.返回
        return recommendUser;
    }

    // 查询推荐用户
    @Override
    public PageBeanVo findRecommendUserByPage(Long toUserId, Integer pageNum, Integer pageSize) {
        // 1.构建条件
        Integer index = (pageNum - 1) * pageSize + 1;
        Query query = Query.query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(index).limit(pageSize);

        // 2.查询list
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
        // 3.查询total
        long total = mongoTemplate.count(query, RecommendUser.class);
        // 4.返回并分装pageBeanVo
        return new PageBeanVo(pageNum, pageSize, total, list);
    }

    /**
     * @param toUserId 你的id
     * @param userId   佳人的id
     * @return
     */
    @Override
    public RecommendUser findRecommendUserByCondition(Long toUserId, Long userId) {
        // 1.构建条件
        Query query = Query.query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        // 2.查询一条
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        // 3.返回
        return recommendUser;
    }
}
